package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.api.publics.dto.response.LocationResDTO;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.model.dto.PageQueryDTO;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.NumberUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.domain.AddressBookSelectDto;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Slf4j
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    @Override
    public void Insert(AddressBookUpsertReqDTO dto) {
        AddressBook bean = BeanUtil.toBean(dto, AddressBook.class);
        Long userId = UserContext.currentUserId();
        if(ObjectUtil.isEmpty(bean)) {
            throw new BadRequestException("添加地址错误");
        }
        if (dto.getIsDefault() == 1){
            lambdaUpdate().eq(AddressBook::getUserId, userId)
                    .set(AddressBook::getIsDefault,0)
                    .update();
        }
        String location = dto.getLocation();
        log.info("经纬度：" + location);
        String[] split = location.split(",");

        Double lon = Double.valueOf(split[0]);
        Double lat = Double.valueOf(split[1]);
        bean.setLon(lon);
        bean.setLat(lat);
        bean.setUserId(userId);
        boolean save = save(bean);
        if(!save) {
            throw new BadRequestException("添加地址错误");
        }
    }

    @Override
    public PageResult<AddressBookSelectDto> select(PageQueryDTO dto) {
        Long userId = UserContext.currentUserId();
        Page<AddressBook> page = PageUtils.parsePageQuery(dto, AddressBook.class);
        LambdaQueryWrapper<AddressBook> wrapper = Wrappers.<AddressBook>lambdaQuery()
                .eq(AddressBook::getUserId,userId)
                .eq(AddressBook::getIsDeleted,0);
        Page<AddressBook> addressBookPage = baseMapper.selectPage(page, wrapper);
        return PageUtils.toPage(addressBookPage, AddressBookSelectDto.class);
    }

    @Override
    public AddressBookSelectDto selectId(Long id) {
        AddressBook addressBook = baseMapper.selectById(id);
        return BeanUtil.copyProperties(addressBook, AddressBookSelectDto.class);
    }

    @Override
    public void putId(AddressBookUpsertReqDTO dto, Long id) {
        AddressBook bean = BeanUtil.toBean(dto, AddressBook.class);
        Long userId = UserContext.currentUserId();
        if (dto.getIsDefault() == 1){
            lambdaUpdate().eq(AddressBook::getUserId, userId)
                    .set(AddressBook::getIsDefault,0)
                    .update();
        }

        //编译地址得到经纬度
        Map<String, Object> params = new HashMap();
        params.put("address", dto.getAddress());
        params.put("key", "a4847d86d136200240220fd86b7f44c0");
        String jsonStr = HttpRequest.get("https://restapi.amap.com/v3/geocode/geo?").form(params).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        JSONArray geocodes = JSONUtil.parseArray(jsonObject.get("geocodes"));
        Object location = JSONUtil.parseObj(geocodes.get(0)).get("location");


        String locationString = location.toString();
        String[] split = locationString.split(",");

        Double lon = Double.valueOf(split[0]);
        Double lat = Double.valueOf(split[1]);
        bean.setLon(lon);
        bean.setLat(lat);

        boolean update = lambdaUpdate()
                .eq(AddressBook::getId, id)
                .set(AddressBook::getAddress, bean.getAddress())
                .set(AddressBook::getCity, bean.getCity())
                .set(AddressBook::getCounty, bean.getCounty())
                .set(AddressBook::getProvince, bean.getProvince())
                .set(AddressBook::getIsDefault, bean.getIsDefault())
                .set(AddressBook::getPhone, bean.getPhone())
                .set(AddressBook::getName, bean.getName())
                .set(AddressBook::getLat, bean.getLat())
                .set(AddressBook::getLon, bean.getLon())
                .update();
        if (!update){
            throw new BadRequestException("更新地址错误");
        }
    }

    @Override
    public void deleteIds(List<String> ids) {
        for (String sid : ids) {
            String replace = sid.replace(":", "");
            log.info("得到的数" + replace);
            Long id = Long.valueOf(replace);
            lambdaUpdate().eq(AddressBook::getId, id)
                    .set(AddressBook::getIsDeleted, 1)
                    .update();
        }
    }

    @Override
    public void defaultOne(int flag, long id) {
        Long userId = UserContext.currentUserId();
        lambdaUpdate()
                .eq(AddressBook::getUserId, userId)
                .set(AddressBook::getIsDefault,0)
                .update();
        lambdaUpdate()
                .eq(AddressBook::getId,id)
                .set(AddressBook::getIsDefault,flag)
                .update();
    }

    @Override
    public AddressBookSelectDto selectDefault() {
        Long userId = UserContext.currentUserId();
        List<AddressBook> list = lambdaQuery()
                .eq(AddressBook::getIsDefault, 1)
                .eq(AddressBook::getUserId, userId)
                .list();
        if (list == null || list.isEmpty()) {
            throw new BadRequestException("您没有设置默认地址");
        }
        AddressBook addressBook = list.get(0);
        return BeanUtil.copyProperties(addressBook, AddressBookSelectDto.class);
    }

}
